import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'

let loadingInstance = null

const service = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器：自动携带Token + 全局loading
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    // 全局loading（可通过config自定义关闭）
    if (config.loading !== false) {
      loadingInstance = ElLoading.service({ fullscreen: true, text: '加载中...' })
    }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器：统一处理code、message、异常 + 关闭loading
service.interceptors.response.use(
  response => {
    if (loadingInstance) loadingInstance.close()
    const res = response.data
    if (res.code !== 200) {
      // 允许外部自定义不弹message
      if (response.config.showMessage !== false) {
        ElMessage.error(res.message || '请求失败')
      }
      // 401/403跳转登录
      if (res.code === 401 || res.code === 403) {
        localStorage.removeItem('token')
        window.location.href = '/login'
      }
      return Promise.reject(res)
    }
    return res.data
  },
  error => {
    if (loadingInstance) loadingInstance.close()
    ElMessage.error(error.response?.data?.message || error.message || '网络异常')
    return Promise.reject(error)
  }
)

export default service 